<template>
  <div class="comment-reply">
    <!-- 导航栏 -->
    <van-nav-bar :title="`${comment.reply_count}条回复`">
      <van-icon slot="left" name="cross" @click="$emit('click-close')" />
    </van-nav-bar>
    <!-- /导航栏 -->

    <!-- 当前评论项 -->
    <comment-item
      :item="comment"
      @toggleLiked="
        comment.is_liking = !comment.is_liking
        comment.like_count = comment.like_count + $event
      "
    ></comment-item>
    <!-- /当前评论项 -->

    <van-cell title="所有回复" />

    <!-- 评论的回复列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      class="listReply"
    >
      <comment-item
        v-for="(item, index) in list"
        :key="index"
        :item="item"
        @toggleLiked="
          item.is_liking = !item.is_liking
          item.like_count = item.like_count + $event
        "
      ></comment-item>
    </van-list>
    <!-- /评论的回复列表 -->

    <!-- 底部 -->
    <van-popup v-model="showComment" position="bottom" :overlay="false">
      <comment-pop :target="comment.com_id.toString()" :art_id="art_id"></comment-pop>
    </van-popup>
    <!-- /底部 -->
  </div>
</template>

<script>
// 导入评论cell
import commentItem from '@/components/comment-cell'
// 导出获取回复评论的api
import { getArtCommnet } from '@/assets/api/comment'
// 导入写评论模块
import commentPop from './commentPopup.vue'
// 导入通信组件
import eventHub from '@/assets/utils/communication'

export default {
  name: 'CommentReply',
  components: { 'comment-item': commentItem, 'comment-pop': commentPop },
  props: {
    comment: {
      type: Object,
      required: true
    },
    art_id: {
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      // 获取回复评论的请求参数
      getReplyParams: {
        type: 'c',
        source: '',
        offset: undefined,
        limit: undefined
      },
      // 列表配置项
      list: [],
      loading: false,
      finished: false,
      // 评论弹出层
      showComment: true
    }
  },
  computed: {},
  watch: {
    comment(val) {
      this.list = []
      this.finished = false
    }
  },
  created() {},
  mounted() {
    eventHub.$on('addComment', (val) => {
      this.list.unshift(val)
    })
  },
  methods: {
    async onLoad() {
      // 发起ajax请求
      this.getReplyParams.source = this.comment.com_id.toString()
      try {
        var { data: res } = await getArtCommnet(this.getReplyParams)
      } catch {
        // 处理错误请求
        this.loading = false
        return this.$toast('回复评论获取失败')
      }
      // 将请求值进行保存
      console.log(res)
      this.getReplyParams.offset = res.data.last_id
      setTimeout(() => {
        this.list.push(...res.data.results)
      }, 100)
      this.loading = false
      // 如果返回数据为0 着结束
      if (!res.data.results.length) {
        this.finished = true
      }
    }
  }
}
</script>

<style scoped>
.listReply {
  height: 700px;
  overflow: scroll;
}
</style>
